<?php

class SmartMySQL extends SmartMySQLBase {

	public function retrieve($column, $table, $field, $value, $other = null)
	{
		if (is_numeric($value) === false) {
			$value = '\'' . $value . '\'';
		}
		$sql = 'SELECT `' . $column . '` FROM `' . $table . '` WHERE `' . $field . '` = ' . $value . ($other == true ? ' ' . $other : null) . ';';
		$this->execute($sql);
		$ret = mysql_result($this->resource, 0, $column);
		return $ret === false ? $ret : false;
	}

	public function numRows()
	{
		$num = mysql_num_rows($this->resource);
		return $num === false ? false : $num;
	}

	public function insertId()
	{
		$id = mysql_insert_id($this->resource);
		return $id === false ? false : $id;
	}

	public function affectedRows()
	{
		$num = mysql_affected_rows($this->resource);
		return $num === false ? false : $num;
	}

	public function bind($query, $parameters = array())
	{
		if (is_array($parameters) === false) {
			trigger_error('Parameter(s) must be an array!');
		}
		$sql = str_replace(array('?', '\'?\'', '"?"'), '%s', $query, $num);
		if ($num !== count($parameters)) {
			exit('error bliad, raodenoba unda sheesabamebodes!');
		}
		foreach ($parameters as $par) {
			switch (gettype($par)) {
				case 'boolean':
				case 'integer':
				case 'double':
					$replace[] = $par;
				break;
				case 'NULL':
					$replace[] = 'NULL';
				break;
				case 'array':
				case 'object':
				case 'resource':
					exit('array, object and resource types are unsupported.');
				default:
					$replace[] = '\'' . $par . '\'';
				break;
			}
		}
		return vsprintf($sql, $replace);
	}

	public function insert($table, $data = array(), $autorun = false)
	{
		if (is_string($table) === false) {
			trigger_error('table-s saxeli string unda ikos!');
		}
		if (is_array($data) === false) {
			trigger_error('argumenti array unda ikos!');
		}
		$fields = $columns = null;
		foreach ($data as $k => $v) {
			$fields .= '`' . $k . '`, ';
			$columns .= is_numeric($v) === true ? $v . ', ' : '\'' . $this->escape($v) . '\', ';
		}
		$sql = 'INSERT INTO `' . $table . '` (' . substr($fields, 0, -2) . ') VALUES (' . substr($columns, 0, -2) . ');';
		return $autorun === true ? $this->execute($sql) : $sql;
	}

	public function update($table, $data = array(), $other = null, $autorun = false)
	{
		if (is_string($table) === false) {
			trigger_error('table-s saxeli string unda ikos!');
		}
		if (is_array($data) === false) {
			trigger_error('argumenti array unda ikos!');
		}
		$set = null;
		foreach ($data as $k => $v) {
			$set .= '`' . $k . '` = ' . (is_numeric($v) === true ? $v . ', ' : '\'' . $this->escape($v) . '\', ') . ', ';
		}
		$sql = 'UPDATE `' . $table . '` SET ' . substr($set, 0, -2) . ($other == true ? ' ' . $other : null) . ' ;';
		return $sql;
	}


}

?>